using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using Microsoft.Extensions.Logging;
using ShopForWeb.Model.Basic;
using ShopForWeb.Services;
using ShopForWeb.UI.Models;


namespace ShopForWeb.UI.Areas.Admin.Controllers
{
  [Area("admin")]
  [Route("[area]/[controller]")]
  public class ProductController : Controller
  {
    private readonly ILogger<ProductController> _logger;
    private ProductService _productService;
    private IWebHostEnvironment _webHost;
    public ProductController(ILogger<ProductController> logger, ProductService productService, IWebHostEnvironment webHost)
    {
      _logger = logger;
      _productService = productService;
      _webHost=webHost;

    }

    public async Task<IActionResult> IndexAsync([FromQuery] int page = 1, [FromQuery] int size = 16, [FromQuery] int statusCode = 0,
    [FromQuery]string key="",[FromQuery]long[] ids=null!)
    {
      var result = await _productService.GetByPageAsync(page, size, statusCode,key,ids);
      return Json(result);
      //return View();
    }
    [HttpPost]

    public async Task<IActionResult> AddNew([FromForm] ShopForWeb.Model.Basic.Product product,[FromForm] IFormFile photoFile)
    {
      if(photoFile!=null)
      {
        string fileName=Guid.NewGuid().ToString("N")+".jpg";
        string path=_webHost.WebRootPath+$@"\upload\{fileName}";

        using(var fs =new FileStream(path,FileMode.Create))
        {
           await photoFile.CopyToAsync(fs);
           product.Photo=fileName;
        }
      }
      int result = await _productService.AddNewAsync(product);
      if (result == 1)
      {
        return Json(new ResponseViewModel()
        {
          Code = 200,
          Message = "商品添加成功"
        });
      }

      else
      {
        return Json(new ResponseViewModel()
        {
          Code = 500,
          Message = "商品添加失败"
        });
      }
    }

    [HttpPut]
    public async Task<IActionResult> ModifyAsync([FromBody] ShopForWeb.Model.Basic.Product product)
    {
      int result = await _productService.ModifyAsync(product);
      if (result == 1)
      {
        return Json(new ResponseViewModel()
        {
          Code = 200,
          Message = "商品修改成功"
        });
      }

      else
      {
        return Json(new ResponseViewModel()
        {
          Code = 500,
          Message = "商品修改失败"
        });
      }
    }

    [HttpDelete("{productId}")]
    public async Task<IActionResult> Remove([FromRoute] int productId)
    {
      int result = await _productService.RemoveAsync(productId);
      if (result == 1)
      {
        return Json(new ResponseViewModel()
        {
          Code = 200,
          Message = "商品删除成功"
        });
      }

      else
      {
        return Json(new ResponseViewModel()
        {
          Code = 500,
          Message = "商品删除失败"
        });
      }
    }
    [ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
    //修改商品状态
    [HttpPut("{productId}/status/{statusCode}")]
    public async Task<IActionResult> ModifyStatusAsync([FromRoute] int productId, int statusCode)
    {
      int result = await _productService.ModifyStatusAsync(productId, statusCode);
      if (result == 1)
      {
        return Json(new ResponseViewModel()
        {
          Code = 200,
          Message = "商品状态修改成功"
        });
      }

      else
      {
        return Json(new ResponseViewModel()
        {
          Code = 500,
          Message = "商品状态修改失败"
        });
      }
    }
     public async Task<IActionResult> Modify([FromForm] ShopForWeb.Model.Basic.Product product,IFormFile photoFile)
        {
            if(photoFile!=null)
            {
                string fileName=String.IsNullOrEmpty(product.Photo)?Guid.NewGuid().ToString("N")+"jpg":product.Photo;
                string path=_webHost.WebRootPath +$@"\upload\{fileName}";
                using(var fs=new FileStream(path,FileMode.Create))
                {
                   await photoFile.CopyToAsync(fs);
                   product.Photo=fileName;
                }
            }
            int result = await _productService.ModifyAsync(product);
            if (result == 1)
                return Json(new ResponseViewModel()
                {
                    Code = 200,
                    Message = "商品修改成功"
                });
            else
                return Json(new ResponseViewModel()
                {
                    Code = 500,
                    Message = "商品修改失败"
                });
        }


  }
}